//
//  ContentViewController.m
//  eBook
//
//  Created by zhy on 12-11-29.
//  Copyright (c) 2012年 zhan. All rights reserved.
//

#import "ContentViewController.h"
#import "NoteViewController.h"
#import "LabelViewController.h"
#import "AppDelegate.h"
#import "NoteDetailViewController.h"
#import "CustomPopoverBackgroundView.h"
#import "SVProgressHUD.h"
#import "QandAViewController.h"
#import "WebLinkViewController.h"
#import "CheckNetwork.h"

@interface ContentViewController ()

@end

@implementation ContentViewController

@synthesize webView;
@synthesize buttomSlider;
@synthesize URLString;
@synthesize ContentVCDelegeta;

#pragma mark - lifecycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"content view did load");
    
    ismenuViewShow = YES;
    
    //webview
    webView.delegate =self;
    webView.scrollView.delegate =self;
    webView.scrollView.pagingEnabled = YES;
    webView.scrollView.clipsToBounds = NO;
    webView.scrollView.showsHorizontalScrollIndicator =NO;
    webView.scrollView.alwaysBounceVertical = NO; // 不能上下弹动
    webView.scrollView.alwaysBounceHorizontal = NO;
    webView.scrollView.scrollEnabled = NO;
//    webView.scrollView.bounces = YES;
    
    //View
    menuView = [self.view viewWithTag:1];
    butttomView = [self.view viewWithTag:2];
    
    HideView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, 1024, 748)];
    HideView.backgroundColor = [UIColor colorWithRed:76/255 green:76/255 blue:76/255 alpha:0.5];
//    [self.view addSubview:HideView];
    [self.view insertSubview:HideView aboveSubview:self.menuContainerView];

    [HideView setHidden:YES];
    
    
    
    //tap Gestuer
    UITapGestureRecognizer *tabRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapHandle:)];
    tabRecognizer.numberOfTapsRequired = 2;
    tabRecognizer.delegate=self;
    
    [webView addGestureRecognizer:tabRecognizer];
    
    UITapGestureRecognizer *tabHidKBRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenAction:)];
    tabHidKBRecognizer.numberOfTapsRequired = 1;
    [HideView addGestureRecognizer:tabHidKBRecognizer];
 
    //Menu Controller
    menuController = [UIMenuController sharedMenuController];
    addNoteMenuItem = [[UIMenuItem alloc] initWithTitle:@"添加笔记" action: @selector(MenuItemAddNoteAction:)];
    [menuController setMenuItems:[NSArray arrayWithObjects:addNoteMenuItem,nil]];
    
    
    isQandAshow = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    [self loadContentHTML];
}

- (void)viewDidUnload
{
    [self setWebView:nil];
    [self setButtomSlider:nil];
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft||interfaceOrientation==UIInterfaceOrientationLandscapeRight);
}

//ios 6 rotation
-(NSUInteger)supportedInterfaceOrientations{
//     return UIInterfaceOrientationLandscapeLeft;//xcode 4.4
    return UIInterfaceOrientationMaskLandscape;//xcode 4.5
}

- (BOOL)shouldAutorotate
{
    return YES;
}


#pragma mark - private methods
-(void) showOrHiddenMenuAndButtomView{
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    //        [UIView setAnimationDelay:0.5];
    [UIView setAnimationDelegate:self];
//    [UIView setAnimationDidStopSelector:@selector(showMenuStop)];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
    
    if (ismenuViewShow) {
        ismenuViewShow = NO;
//        menuView.hidden = YES;
//        butttomView.hidden = YES;
        menuView.frame = CGRectMake(0, -60, 1024, 60);
        butttomView.frame = CGRectMake(0, 748, 1024, 40);
    } else {
        ismenuViewShow = YES;
//        menuView.hidden = NO;
//        butttomView.hidden = NO;
        menuView.frame = CGRectMake(0, 0, 1024, 60);
        butttomView.frame = CGRectMake(0, 708, 1024, 40);
    }
    
    [UIView commitAnimations];
}

-(NSString *)getURLofScreenshot
{
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
    NSString *dateString = [dateFormat stringFromDate:today];
    
    //tem
    //    NSString  *pngPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Screenshot %@.png",dateString]];
    
    //Caches
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *pngPath = [paths objectAtIndex:0];
    pngPath = [pngPath stringByAppendingPathComponent:[NSString stringWithFormat:@"Screenshot%@.png",dateString]];
    
    UIGraphicsBeginImageContext(self.webView.frame.size);
    [self.webView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *saveImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [UIImagePNGRepresentation(saveImage) writeToFile:pngPath atomically:YES];
    
    return pngPath;
}

-(void) setChapter:(int)chapter andFeature:(int)feature andPage:(int)page andAllPages:(int)allpagecount andFeatureCount:(int)featureCount{
    currentChapter = chapter;
    currentPage = page;
    currentFeature = feature;
    FeatureCount = featureCount;
}

-(void) loadContentHTML{
    [buttomSlider setUserInteractionEnabled:NO];
    [webView setUserInteractionEnabled:NO];
    
    if (CheckNetwork.check) {
        [SVProgressHUD showWithStatus:@"加载数据..."];    
        if (currentChapter <= 9) {
            URLString = [NSString stringWithFormat:@"http://211.66.111.97:8080/%d/index.html", currentFeature];
        } else {
            URLString = [NSString stringWithFormat:@"http://jpkc.gdou.com/ebook/%d/%d.html",currentChapter,currentFeature];
        }
        NSLog(@"URLString is %@",URLString);
        NSURL *url = [NSURL URLWithString:URLString];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];
    }
}

#pragma mark - Responding to keyboard events
- (void)keyboardWillShow:(NSNotification *)notification {
    
    if (isQandAshow) {
        NSDictionary *userInfo = [notification userInfo];
        
        NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        
        CGRect keyboardRect = [aValue CGRectValue];
        
        NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
        NSTimeInterval animationDuration;
        [animationDurationValue getValue:&animationDuration];
        
//        NSLog(@"keyboardRect.size %@",NSStringFromCGSize(keyboardRect.size));
//        NSLog(@"enterview frame %@",NSStringFromCGRect(QandAVC.enterView.frame));
//        NSLog(@"tableview frame %@",NSStringFromCGRect(QandAVC.chatTableView.frame));
        
        //init frame
        QandAVC.enterView.frame = CGRectMake(14, 600, 284, 48);
        QandAVC.chatTableView.frame = CGRectMake(0, 0, 300, 600);
        
        [UIView beginAnimations:@"kyy board up" context:(void *)QandAVC.view];
        [UIView setAnimationDuration:animationDuration];
        QandAVC.enterView.frame = CGRectMake(14, 600-keyboardRect.size.width+40, 284, 48);
        QandAVC.chatTableView.frame = CGRectMake(0, 0, 300, 600-keyboardRect.size.width+40);
        [QandAVC.chatTableView setContentOffset:CGPointMake(0, QandAVC.chatTableView.contentSize.height-QandAVC.chatTableView.frame.size.height)];
        [UIView commitAnimations];
        
//        NSLog(@"enterview frame %@",NSStringFromCGRect(QandAVC.enterView.frame));
        
    }
    
}

- (void)keyboardWillHide:(NSNotification *)notification {
    if (isQandAshow) {
        NSDictionary *userInfo = [notification userInfo];
        
        NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        
        CGRect keyboardRect = [aValue CGRectValue];
        
        NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
        NSTimeInterval animationDuration;
        [animationDurationValue getValue:&animationDuration];
        
        [UIView beginAnimations:@"kyy board down" context:(void *)QandAVC.view];
        [UIView setAnimationDuration:animationDuration];
        QandAVC.enterView.frame = CGRectMake(14, 600, 284, 48);
        QandAVC.chatTableView.frame = CGRectMake(0, 0, 300, 600);
        [QandAVC.chatTableView setContentOffset:CGPointMake(0, QandAVC.chatTableView.contentSize.height-QandAVC.chatTableView.frame.size.height)];
        [UIView commitAnimations];
        
    }
}
#pragma mark - Segue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
    if ([segue.identifier isEqualToString:@"notePopoverSegue"]) {
        
        NoteViewController *noteVC = segue.destinationViewController;
        noteVC.NoteVCDelegate = self;
        
        UIStoryboardPopoverSegue *popsegue = (UIStoryboardPopoverSegue *)segue;
        NotePopoverC = popsegue.popoverController;
        
//        NotePopoverC.popoverBackgroundViewClass = [CustomPopoverBackgroundView class];
    
        
    } else if([segue.identifier isEqualToString:@"labelPopoverSegue"]){
        
        LabelViewController *labelVC = (LabelViewController *)segue.destinationViewController;
        labelVC.LabelVCDelegate = self;
        [labelVC setChapter:currentChapter andFeature:currentFeature andPage:currentPage];

        [labelVC loadDataFromCoreData];
        
        
        UIStoryboardPopoverSegue *popsegue = (UIStoryboardPopoverSegue *)segue;
        LabelPopoverC = popsegue.popoverController;
        
//        LabelPopoverC.popoverBackgroundViewClass = [CustomPopoverBackgroundView class];
        
        
    } else if ([segue.identifier isEqualToString:@"noteDetailSegue"]){
//        NoteDetailViewController *noteDetailVC = segue.destinationViewController;
        
    } else if ([segue.identifier isEqualToString:@"weblinkSegue"]){
        WebLinkViewController *webLinkVC = segue.destinationViewController;
        webLinkVC.URLString = webLink;
    } else if ([segue.identifier isEqualToString:@"MenuToNote"]){
        NewNoteViewController *noteVC = segue.destinationViewController;
        noteVC.NewNoteVCDelegate = self;
        noteVC.view.frame = CGRectMake(0, 0, 500, 768);
        [HideView setHidden:NO];
    } else if ([segue.identifier isEqualToString:@"MenuToDU"]){
        DownloadUploadViewController *dUVC = segue.destinationViewController;
        dUVC.DUVCDelegate = self;
        dUVC.view.frame = CGRectMake(0, 0, 500, 768);
        dUVC.duString = @"上传";
        [HideView setHidden:NO];
    } else if ([segue.identifier isEqualToString:@"MenuToDownload"]){
        DownloadUploadViewController *downloadDUVC = segue.destinationViewController;
        downloadDUVC.DUVCDelegate = self;
        downloadDUVC.view.frame = CGRectMake(0, 0, 500, 768);
        downloadDUVC.duString = @"下载";
        [HideView setHidden:NO];
    } else if ([segue.identifier isEqualToString:@"MenuToComment"]){
        CommentViewController *commentDUVC = segue.destinationViewController;
        commentDUVC.CommentVCDelegate = self;
        commentDUVC.view.frame = CGRectMake(0, 0, 500, 768);
        [HideView setHidden:NO];
    } else if ([segue.identifier isEqualToString:@"MenuToBookmark"]){
        NewBookmarkViewController *bookmarkVC = segue.destinationViewController;
        bookmarkVC.NewBookmarkDelegate = self;
        bookmarkVC.feature = [NSString stringWithFormat:@"%d", currentFeature];
        switch (currentFeature)
        {
            case 1:
                bookmarkVC.image = [UIImage imageNamed:@"cover.png"];
                bookmarkVC.content = @"问卷调查法：问卷组成";
                break;
            case 2:
                bookmarkVC.image = [UIImage imageNamed:@"cover.png"];
                bookmarkVC.content = @"问卷调查法：制定问卷";
                break;
            case 3:
                bookmarkVC.image = [UIImage imageNamed:@"cover.png"];
                bookmarkVC.content = @"问卷调查法：发放问卷";
                break;
            default:
                break;
        }
        bookmarkVC.view.frame = CGRectMake(0, 0, 500, 768);
        [HideView setHidden:NO];
    }
}

#pragma mark - IBAction

- (IBAction)buttomSliderAction:(id)sender {
    
    currentPage = (int)[buttomSlider value] ;
    
    [self.webView.scrollView setContentOffset:CGPointMake((currentPage-1)*pageWidth, 0) animated:YES];
}

- (IBAction)backMenuAction:(id)sender {
    
    [SVProgressHUD dismiss];
    
    [ContentVCDelegeta back:currentChapter];
    [self dismissViewControllerAnimated:YES completion:^{
        [ContentVCDelegeta back:currentChapter];
    }];
    
}

- (IBAction)SharingAction:(id)sender {
    
    [HideView setHidden:NO];
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate setVCForSina:self];

    
    SharingVC = [[SharingViewController alloc] initWithNibName:@"SharingViewController" bundle:nil];
    SharingVC.view.frame = CGRectMake(272, 1024, 480, 404);
    addNoteVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"share_bg.png"]];
    [SharingVC.ShareSinaLogInBtn addTarget:self action:@selector(ShareSinaLogInBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [SharingVC.ShareBtn addTarget:self action:@selector(ShareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [SharingVC.ShareCancelBtn addTarget:self action:@selector(ShareCancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    SharingVC.ShareContetTextView.backgroundColor = [UIColor colorWithRed:232/255 green:232/255 blue:232/255 alpha:0.1];
    SharingVC.ShareContetTextView.delegate =self;
    [self.view addSubview:SharingVC.view];
    
    
    [UIView beginAnimations:@"go Sharing View" context:(void *)SharingVC.view];
    [UIView setAnimationDuration:0.5];
    SharingVC.view.frame = CGRectMake(272, 100, 480, 404);
    [UIView commitAnimations];
    
    int check = CheckNetwork.check;
    
}

- (IBAction)backCoverAction:(id)sender {
    
    [SVProgressHUD dismiss];
    
    [ContentVCDelegeta showCover];
    [self dismissViewControllerAnimated:YES completion:^{
        NSLog(@"dismiss done");
        [ContentVCDelegeta showCover];//for ipad 1 memory
    }];
}

- (IBAction)QandAAction:(id)sender {
    
    if (isQandAshow) {
        
        if ([QandAVC.sendTextField isFirstResponder]) {
            [QandAVC.sendTextField resignFirstResponder];
        }
        
        [UIView beginAnimations:@"Q and A  View hidden" context:(void *)QandAVC.view];
        [UIView setAnimationDuration:0.5];
        QandAVC.view.frame = CGRectMake(724, -1000, 300, 648);
        [UIView commitAnimations];
    
        //hide View
        [HideView setHidden:YES];
        [HideView setBackgroundColor:[UIColor colorWithRed:76/255 green:76/255 blue:76/255 alpha:0.5]];
        
        
        isQandAshow = NO;
        
    } else {
        if (!QandAVC) {
            QandAVC = [[QandAViewController alloc] initWithNibName:@"QandAViewController" bundle:nil];
            QandAVC.view.frame = CGRectMake(724, -1000, 300, 648);
            QandAVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"dy_background.png"]];
            
            [self.view insertSubview:QandAVC.view belowSubview:menuView];
//            [self.view addSubview:QandAVC.view];
        }
        
        //show view
        [HideView setHidden:NO];
        [HideView setBackgroundColor:[UIColor clearColor]];
        
        [UIView beginAnimations:@"Q and A  View show" context:(void *)QandAVC.view];
        [UIView setAnimationDuration:0.5];
        QandAVC.view.frame = CGRectMake(724, 60, 300, 648);
        [UIView commitAnimations];
        
        isQandAshow = YES;
        
        int check = CheckNetwork.check;
        
    }
}

- (IBAction)backIndexAction:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)hideAndShowMenuAction:(id)sender
{
    if (webView.frame.origin.x > 0)
    {
        [UIView beginAnimations:@"Menu hide" context:nil];
        [UIView setAnimationDuration:0.3];
        webView.frame = CGRectMake(0, 0, 1024, 768);
        self.toolbar.frame = CGRectMake(0, 20, 1024, 44);
        self.menuContainerView.frame = CGRectMake(-200, 20, 200, 748);
        [UIView commitAnimations];
    }
    else
    {
        webView.frame = CGRectMake(0, 64, 1024, 704);
        [UIView beginAnimations:@"Menu show" context:nil];
        [UIView setAnimationDuration:0.3];
        webView.frame = CGRectMake(200, 64, 824, 704);
        self.toolbar.frame = CGRectMake(200, 20, 824, 44);
        self.menuContainerView.frame = CGRectMake(0, 20, 200, 748);
        [UIView commitAnimations];
    }
}

- (IBAction)noteAction:(id)sender
{
    
}

- (IBAction)bookmarkAction:(id)sender
{
    
}

- (IBAction)upLoadAction:(id)sender
{
    
}

- (IBAction)downloadAction:(id)sender
{
    
}

- (IBAction)commentAction:(id)sender
{
    
}

- (IBAction)shareAction:(id)sender
{
    [HideView setHidden:NO];
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [delegate setVCForSina:self];
    
    
    SharingVC = [[SharingViewController alloc] initWithNibName:@"SharingViewController" bundle:nil];
    SharingVC.view.frame = CGRectMake(272, 1024, 480, 404);
    addNoteVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"share_bg.png"]];
    [SharingVC.ShareSinaLogInBtn addTarget:self action:@selector(ShareSinaLogInBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [SharingVC.ShareBtn addTarget:self action:@selector(ShareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [SharingVC.ShareCancelBtn addTarget:self action:@selector(ShareCancelBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    SharingVC.ShareContetTextView.backgroundColor = [UIColor colorWithRed:232/255 green:232/255 blue:232/255 alpha:0.1];
    SharingVC.ShareContetTextView.delegate =self;
    [self.view addSubview:SharingVC.view];
    
    
    [UIView beginAnimations:@"go Sharing View" context:(void *)SharingVC.view];
    [UIView setAnimationDuration:0.5];
    SharingVC.view.frame = CGRectMake(272, 100, 480, 404);
    [UIView commitAnimations];
}

- (IBAction)searchAction:(id)sender
{
    
}

- (IBAction)settingAction:(id)sender
{
    
}

-(void) MenuItemAddNoteAction:(UIMenuController *) sender{
    NSLog(@"class is %@",[sender class]);
    
    NSString* selection = [self.webView stringByEvaluatingJavaScriptFromString:@"window.getSelection().toString()"];
    
    NSLog(@"selection is %@",selection);
    
    [self AddNote];
    addNoteVC.NoteContent.text = selection;
    
}

- (void)saveNewNote:(id)sender {
    if ([addNoteVC.NoteContent.text isEqualToString:@""]) {
        NSLog(@" null");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"笔记内容不能为空"
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles: nil];
        [alert show];
    } else {
        NSLog(@"not null ");
        
        [HideView setHidden:YES];
        
        [UIView beginAnimations:@"go addNote View" context:(void *)addNoteVC.view];
        [UIView setAnimationDuration:0.5];
        addNoteVC.view.frame = CGRectMake(237, 1024, 550, 342);
        [UIView commitAnimations];
        
        //保存进core data
        AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
        NSManagedObjectContext *context = appDelegate.managedObjectContext;
        NSEntityDescription *entityDescription = [NSEntityDescription
                                                  entityForName:@"Note"
                                                  inManagedObjectContext:context];
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:entityDescription];
        NSError *error;
        NSArray *objects = [context executeFetchRequest:request error:&error];
        NSManagedObject *oneObject;
        if (objects == nil) {
            NSLog(@"core data have not object,there was a error!");
        }

        oneObject = [NSEntityDescription
                     insertNewObjectForEntityForName:@"Note"
                     inManagedObjectContext:context];

        [oneObject setValue:[NSNumber numberWithInt:currentChapter] forKey:@"chapter"];
//        [oneObject setValue:title forKey:@"title"];
        [oneObject setValue:addNoteVC.NoteContent.text forKey:@"content"];
        
        [appDelegate saveContext];
        
        NSLog(@"save one note ,chapter is %d, content:%@",currentChapter,addNoteVC.NoteContent.text);
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"笔记保存成功"
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles: nil];
        [alert show];
        
//        NoteTitle.text = @"";
        addNoteVC.NoteContent.text = @"";
        
        [menuController setMenuItems:[NSArray arrayWithObjects:addNoteMenuItem,nil]];
    }
}

- (void)cancelNewNote:(id)sender {

    [menuController setMenuItems:[NSArray arrayWithObjects:addNoteMenuItem,nil]];
    
    [UIView beginAnimations:@"go addNote View" context:(void *)addNoteVC.view];
    [UIView setAnimationDuration:0.5];
    addNoteVC.view.frame = CGRectMake(237, 1024, 550, 342);
    [UIView commitAnimations];
    
    [HideView setHidden:YES];

    
//    NoteTitle.text = @"";
    addNoteVC.NoteContent.text = @"";
    
}

- (void)ShareBtnAction:(id)sender{
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isAuthValid]) {
        
        if ([self SharingtextLength:SharingVC.ShareContetTextView.text] >=120) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"输入的字数请不要超过140个。" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
            [alert show];
            
        } else {
            
            // post image status
            
            
            NSString *sendText = [NSString stringWithFormat:@"%@,%@",SharingVC.ShareContetTextView.text,[NSDate date]];
            
            [sinaweibo requestWithURL:@"statuses/upload.json"
                               params:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       sendText, @"status",
                                       [UIImage imageNamed:@"SinaImg.png"], @"pic", nil]
                           httpMethod:@"POST"
                             delegate:self];
        }
        
    } else {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录微博帐号" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
        [alert show];
        
    }
    

    

}

- (void) ShareSinaLogInBtnAction:(id)sender{
    
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    if ([sinaweibo isLoggedIn]) {
        [sinaweibo logOut];
        [SharingVC.ShareSinaLogInBtn setTitle:@"账户登录" forState:UIControlStateNormal];
        SharingVC.ShareSinaUserNameLabel.text = @"";
    } else {
        [sinaweibo logIn];
    }

}


- (void) ShareCancelBtnAction:(id)sender{
    SinaWeibo *sinaweibo = [self sinaweibo];
    [sinaweibo logOut];
    
    [UIView beginAnimations:@"go Sharing View" context:(void *)SharingVC.view];
    [UIView setAnimationDuration:0.5];
    SharingVC.view.frame = CGRectMake(272, 1024, 480, 404);
    [UIView commitAnimations];
    
    [HideView setHidden:YES];
}

-(int)SharingtextLength:(NSString *)dataString
{
    float sum = 0.0;
    for(int i=0;i<[dataString length];i++)
    {
        NSString *character = [dataString substringWithRange:NSMakeRange(i, 1)];
        if([character lengthOfBytesUsingEncoding:NSUTF8StringEncoding] == 3)
        {
            sum++;
        }
        else
            sum += 0.5;
    }
    
    return ceil(sum);
}


#pragma mark - GestureHandle
-(void)tapHandle:(UITapGestureRecognizer *) sender{
    NSLog(@"taphandle");
    [self showOrHiddenMenuAndButtomView];
}


-(void)hiddenAction:(UITapGestureRecognizer *) sender{
    if (isQandAshow) {
        
        if ([QandAVC.sendTextField isFirstResponder]) {
            [QandAVC.sendTextField resignFirstResponder];
        } else {
            [self QandAAction:nil];
        }
        
    } else {
        [addNoteVC.NoteContent resignFirstResponder];
        [SharingVC.ShareContetTextView resignFirstResponder];
    }
}


#pragma mark  - UIGestureRecognizerDelegate
//- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
//    return YES;
//}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

#pragma mark  - UIwebViewDelegate
-(void) webViewDidFinishLoad:(UIWebView *)WV{
    
    [SVProgressHUD dismissWithSuccess:@"加载成功！"];
    [webView setUserInteractionEnabled:YES];
    [buttomSlider setUserInteractionEnabled:YES];
    
    //设置滑动分页的页大小
    self.webView.scrollView.frame = CGRectMake(0, 0, 984, 748);
    
    float contentWidth = self.webView.scrollView.contentSize.width;
    pageWidth = self.webView.scrollView.frame.size.width;
    AllPagesCount = contentWidth/pageWidth;
    NSLog(@"AllPagesCount is %d",AllPagesCount);
    buttomSlider.value = currentPage;
    
    [self.webView.scrollView setContentOffset:CGPointMake((currentPage -1)*pageWidth, 0) animated:YES];
    //设置slider
    buttomSlider.minimumValue = 1;
    buttomSlider.maximumValue = AllPagesCount;
    buttomSlider.value = currentPage;
}

-(void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    [SVProgressHUD dismissWithError:@"加载失败！"];
}


-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *requestString = [[request URL] absoluteString];
    NSLog(@"string is %@",requestString);
    
    NSString *ssub = @"zhanhuanyu";
    if (requestString.length>=26) {
        NSRange rng = NSMakeRange(0, 26);
        ssub = [requestString substringWithRange:rng];
        NSLog(@"sub string is %@", ssub);
    }

    if ([ssub isEqualToString:@"http://211.66.111.97:8080/"]) {
        return YES;
    } else {
        [self performSegueWithIdentifier:@"weblinkSegue" sender:self];
        webLink = requestString;
        return NO;
    }
    
}

#pragma mark - UIScrollerViewDelegate

-(void) scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    //设置滑动分页的页大小
    self.webView.scrollView.frame = CGRectMake(0, 0, 984, 748);
    
    
//    NSLog(@"self.view.frame is %@",NSStringFromCGRect(self.view.frame));
//    NSLog(@"self.webView.frame is %@",NSStringFromCGRect(self.webView.frame));
//    NSLog(@"webView.scrollView.contentSize is %@",NSStringFromCGSize(webView.scrollView.contentSize));
//    NSLog(@"webView.scrollView.frame.size is %@",NSStringFromCGSize(webView.scrollView.frame.size));
    
}

-(void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    buttomSlider.value = webView.scrollView.contentOffset.x/pageWidth +1;
    
    currentPage = (int)buttomSlider.value;
    
}

-(void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
//    NSLog(@"end drag %f,%@",webView.scrollView.contentOffset.x,NSStringFromCGSize(webView.scrollView.contentSize));
    
    //拖动到最尾
    if (webView.scrollView.contentSize.width - webView.scrollView.contentOffset.x == 984) {
        NSLog(@"next!!");
        
        if (currentFeature < FeatureCount) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"是否进入下一个专题？"
                                                           delegate:self
                                                  cancelButtonTitle:@"否"
                                                  otherButtonTitles:@"是", nil];
            [alert show];
            
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:@"您已完成本章的学习任务\n继续学习请回目录选择"
                                                           delegate:nil
                                                  cancelButtonTitle:@"知道了"
                                                  otherButtonTitles: nil];
            [alert show];
        }
    }
    
    
    
}

#pragma mark - AlertView

-(void) alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        //重新加载url
        currentFeature = currentFeature+1;
        currentPage = 1;
        [self loadContentHTML];
    }
}

#pragma mark - PopOver Delegate

//Note Popover Delegate
-(void) AddNote{
    
    [NotePopoverC dismissPopoverAnimated:NO];
    [HideView setHidden:NO];
    [menuController setMenuItems:nil];
    
    
    addNoteVC = [[AddNoteViewController alloc] initWithNibName:@"AddNoteViewController" bundle:nil];
    addNoteVC.view.frame = CGRectMake(237, 1024, 550, 342);
    addNoteVC.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"note.png"]];
    [addNoteVC.saveBtn addTarget:self action:@selector(saveNewNote:) forControlEvents:UIControlEventTouchUpInside];
    [addNoteVC.cancelBtn addTarget:self action:@selector(cancelNewNote:) forControlEvents:UIControlEventTouchUpInside];
    addNoteVC.NoteContent.backgroundColor = [UIColor clearColor];
    [self.view addSubview:addNoteVC.view];
    
    
    [UIView beginAnimations:@"go addNote View" context:(void *)addNoteVC.view];
    [UIView setAnimationDuration:0.5];
    addNoteVC.view.frame = CGRectMake(237, 120, 550, 342);
    [UIView commitAnimations];
    
    
}

-(void) CheckNote{
    [NotePopoverC dismissPopoverAnimated:NO];
    [self performSegueWithIdentifier:@"noteDetailSegue" sender:nil];
}

//Label Popover Delegate

-(void) AddLabel{
    NSLog(@"AddLabel");
    //保存进core data
    AppDelegate *appDelegate=[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    NSEntityDescription *entityDescription = [NSEntityDescription
                                              entityForName:@"Label"
                                              inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    NSError *error;
    NSArray *objects = [context executeFetchRequest:request error:&error];
    NSManagedObject *oneObject;
    if (objects == nil) {
        NSLog(@"core data have not object,there was a error!");
    }

    oneObject = [NSEntityDescription
                 insertNewObjectForEntityForName:@"Label"
                 inManagedObjectContext:context];
    
    [oneObject setValue:[NSNumber numberWithInt:currentChapter] forKey:@"chapter"];
    [oneObject setValue:[NSNumber numberWithInt:currentFeature] forKey:@"feature"];
    [oneObject setValue:[NSNumber numberWithInt:currentPage] forKey:@"page"];
    [oneObject setValue:[self getURLofScreenshot] forKey:@"imageURL"];
    
    [appDelegate saveContext];
}

-(void) LabelSelectedwithChapter:(int)chapter andFeature:(int)feature andPage:(int)page{
    
    //重新加载url <--chapter
    currentChapter = chapter;
    currentFeature = feature;
    
    //设置page
    currentPage = page;

    [self loadContentHTML];    
}

-(void) LabelSelectedWithPage:(int)page{
    currentPage = page;
    buttomSlider.value = currentPage;
    [self.webView.scrollView setContentOffset:CGPointMake((currentPage -1)*pageWidth, 0) animated:YES];
}

#pragma mark - Sina TextView Delegate
-(void) textViewDidChange:(UITextView *)textView{
    NSLog(@"text length is %d",[self SharingtextLength:textView.text]);
    
    SharingVC.ShareTextCount.text = [NSString stringWithFormat:@"%d",120-[self SharingtextLength:textView.text]];
    
}

#pragma mark - SinaWeibo Delegate
// 用户成功登陆
// 注意需要将登陆成功的用户信息缓存下来以便下次使用
- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"登录成功");
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate);
    [self storeAuthData];
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                    message:@"登录成功！"
                                                   delegate:self
                                          cancelButtonTitle:@"知道了"
                                          otherButtonTitles: nil];
    
    [alert show];
    
    [SharingVC.ShareSinaLogInBtn setHidden:YES];
    //
    [sinaweibo requestWithURL:@"users/show.json"
                       params:[NSMutableDictionary dictionaryWithObject:sinaweibo.userID forKey:@"uid"]
                   httpMethod:@"GET"
                     delegate:self];
    
}
// 用户退出登陆
// 注意需要清除已经缓存的用户信息
- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo {
    NSLog(@"sinaweiboDidLogOut");
    [self removeAuthData];
}
// 用户取消登陆过程
- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo {
    NSLog(@"sinaweiboLogInDidCancel");
}
// 登陆失败
- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error {
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}
// 缓存的 token 无效或者已经过期
// 注意需要清除缓存的用户信息
- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error {
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    [self removeAuthData];
}
#pragma mark - SinaWeiboRequest Delegate
// 请求失败
- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error {
    // 当一个 delegate 需要处理多个请求回调时,可以通过 url 来判断当前的 request
    if ([request.url hasSuffix:@"users/show.json"])
    {
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"]) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"发送失败！"
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles: nil];
        
        [alert show];
    }
}
// 请求成功
- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result {
    // 当一个 delegate 需要处理多个请求回调时,可以通过 url 来判断当前的 request
    if ([request.url hasSuffix:@"users/show.json"])
    {
        NSLog(@"用户名");
        [SharingVC.ShareSinaLogInBtn setHidden:NO];
        [SharingVC.ShareSinaLogInBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        
        SharingVC.ShareSinaUserNameLabel.text = [result objectForKey:@"screen_name"];
        
        NSLog(@"name is %@",[result objectForKey:@"screen_name"]);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"]) {
        
        [self ShareCancelBtnAction:nil];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"发送成功！"
                                                       delegate:self
                                              cancelButtonTitle:@"知道了"
                                              otherButtonTitles: nil];
        
        [alert show];
    }
//    [self resetButtons];
}

- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}

- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)removeAuthData
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"SinaWeiboAuthData"];
}


#pragma mark - tableView delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    currentFeature = indexPath.row + 1;
    [self loadContentHTML];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    tableView.width = 200;
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    tableView.scrollEnabled = NO;
    
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MenuCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    switch (indexPath.row)
    {
        case 0:
            cell.textLabel.text = @"问卷调查法：问卷组成";
            break;
        case 1:
            cell.textLabel.text = @"问卷调查法：制定问卷";
            break;
        case 2:
            cell.textLabel.text = @"问卷调查法：发放问卷";
            break;
        default:
            break;
    }
    
    cell.textLabel.font = [UIFont fontWithName:@"System" size:4];
    cell.textLabel.textColor = [UIColor colorWithRed:243 green:240 blue:233 alpha:1];
    cell.textLabel.textAlignment = NSTextAlignmentLeft;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row)
    {
        default:
            return 30;
            break;
    }
}

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

#pragma NewNoteVCDelegate

- (void)backToMenu
{
    [HideView setHidden:YES];
}

#pragma DownloadUploadVCDelegate

- (void)dUVCBackToMenu
{
    [HideView setHidden:YES];
}

#pragma CommentVCDegegate

- (void)commentVCBackToMenu
{
    [HideView setHidden:YES];
}

#pragma NewBookmarkVCDelegate

- (void)newBookmarkVCBackToMenu
{
    [HideView setHidden:YES];
}

- (void)loadBookmarkChapter:(int)feature
{
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:feature-1 inSection:0] animated:YES scrollPosition:nil];
    [HideView setHidden:YES];
    currentFeature = feature;
    [self loadContentHTML];
}

@end
